package com.kmb.security.config.service;

import com.google.common.collect.Lists;
import com.kmb.provider.api.SfKmResourcesService;
import com.kmb.provider.api.SfKmUserService;
import com.kmb.provider.domain.SfKmResources;
import com.kmb.provider.domain.SfKmUser;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义用户认证与授权
 * <p>
 * Description:
 * </p>
 *
 * @author Lusifer
 * @version v1.0.0
 * @date 2019-04-04 23:57:04
 * @see com.kmb.security.config
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference(version = "1.0.0")
    private SfKmUserService sfKmUserService;
    @Reference(version = "1.0.0")
    private SfKmResourcesService sfKmResourcesService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SfKmUser tbUser = sfKmUserService.getByUsername(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("USER");
        grantedAuthorities.add(grantedAuthority);
        if (tbUser != null) {
            // 获取用户授权
            List<SfKmResources> sfKmResources = sfKmResourcesService.selectByUserId(tbUser.getUserId());
            // 声明用户授权
            sfKmResources.forEach(sfKmResource -> {
                if (sfKmResource != null && sfKmResource.getNameEn() != null) {
                    GrantedAuthority grantedAuthoritys = new SimpleGrantedAuthority(sfKmResource.getNameEn());
                    grantedAuthorities.add(grantedAuthoritys);
                }
            });
        }
        return new User(tbUser.getUserName(), tbUser.getUserPassword(), grantedAuthorities);
    }
}
